<script setup>
import { ArrowDown, Fold, User, SwitchButton, Expand } from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import { useRouter } from "vue-router";
import { ref, onMounted } from "vue";
import axios from "axios";

// 定义props接收折叠状态
const props = defineProps({
  collapse: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(['toggleCollapse']);
const handleFold = () => {
  emit('toggleCollapse');
};

const router = useRouter()

// 定义用户信息
const user = ref(null)

// 页面加载时从 localStorage 中获取用户信息
onMounted(() => {
  const userData = localStorage.getItem('user')
  if (userData) {
    user.value = JSON.parse(userData)
  }
})

const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => { // 改为async/await
    try {
      // 1. 调用后端退出接口
      await axios.post('http://localhost:8080/user/logout', {}, {
        withCredentials: true // 携带Cookie（关键！）
      });

      // 2. 清除前端存储
      localStorage.removeItem('user');
      localStorage.removeItem('token'); // 如果不再需要可移除

      // 3. 跳转登录页
      await router.replace('/login');

      // 4. 强制刷新（可选）
      window.location.reload();
    } catch (err) {
      console.error('退出失败:', err);
      ElMessage.error('退出失败，请重试');
    }
  }).catch(() => {});
}

const toUser = () => {
  router.push('/home')
}
</script>

<template>
  <div class="header-container">
    <div class="fold-btn" @click="handleFold">
      <!-- 根据父组件传递的collapse状态切换图标 -->
      <el-icon :size="20">
        <component :is="collapse ? Expand : Fold" />
      </el-icon>
    </div>

    <!-- 居中标题 -->
    <div class="title">
      欢迎使用仓库管理系统
    </div>

    <!-- 右侧用户信息 -->
    <div class="user-info">
      <el-dropdown
          placement="bottom-end"
          trigger="hover"
          :show-timeout="200"
          :hide-timeout="300"
          popper-class="user-dropdown"
      >
        <div class="dropdown-trigger">
          <span class="username">{{ user ? user.name : '未登录' }}</span>
          <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
        </div>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="toUser">
              <el-icon><User /></el-icon>
              <span>个人中心</span>
            </el-dropdown-item>
            <el-dropdown-item divided @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              <span>退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<style scoped>
.header-container {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  position: relative; /* 为下拉菜单提供定位基准 */
}

.fold-btn {
  cursor: pointer;
  padding: 8px;
  margin-right: 20px;
  transition: background 0.3s;
}
.fold-btn:hover {
  background: rgba(0,0,0,0.05);
}

.title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 24px;
  white-space: nowrap;
}

.user-info {
  margin-left: auto;
  padding-right: 20px;
}

/* 下拉触发区域样式 */
.dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.3s;
}
.dropdown-trigger:hover {
  background: rgba(0,0,0,0.05);
}

.dropdown-icon {
  font-size: 18px;
  transition: transform 0.3s;
}
.dropdown-trigger:hover .dropdown-icon {
  transform: rotate(180deg);
}

/* 下拉菜单全局样式 */
:deep(.user-dropdown) {
  z-index: 9999 !important;
  margin-top: 5px !important;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  border-radius: 4px;
}

:deep(.user-dropdown .el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  font-size: 14px;
  color: #ffffff;
}

:deep(.user-dropdown .el-dropdown-menu__item:hover) {
  background-color: #f5f7fa;
  color: #409eff;
}

:deep(.user-dropdown .el-icon) {
  font-size: 16px;
  color: #ffffff;
}
</style>
